package com.rxnetwork.sample.utils.interceptor;

import android.content.Context;
import android.util.Log;

import com.rxnetwork.sample.utils.network.AppNetworkAvailable;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 缓存拦截器
 */
public class AppCacheInterceptor implements Interceptor {

    private static final String TAG = "AppCacheInterceptor";

    private Context context;

    public AppCacheInterceptor(Context context) {
        this.context = context;
        Log.i(TAG, "缓存文件目录:" + context.getCacheDir());
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();//获取请求
        if (!AppNetworkAvailable.isNetworkAvailable(context)) {
            request = request.newBuilder()
                    // 缓存策略。
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            Log.d("AppCacheInterceptor", "no network");
        }
        Response originalResponse = chain.proceed(request);
        if (AppNetworkAvailable.isNetworkAvailable(context)) {
            int maxAge = 0;
            return originalResponse.newBuilder()
                    //这里设置的为0就是说不进行缓存，我们也可以设置缓存时间
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .removeHeader("Pragma")
                    .build();
        } else {
            int maxTime = 5 * 24 * 60 * 60;//5天
            return originalResponse.newBuilder()
                    //这里的设置的是我们的没有网络的缓存时间，想设置多少就是多少。
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime)
                    .removeHeader("Pragma")
                    .build();
        }
    }

}